#include "Game.h"

IGame* createGame( HINSTANCE hInst, HWND hWnd )
{
	return new Game( hInst, hWnd );
}

Game::Game( HINSTANCE hInst, HWND hWnd ) :
	m_input( hInst, hWnd )
{
	// initialize camera
	m_camera.hand = Camera::RIGHTHANDED;

	m_camera.eye = float3( 0, 0, 10.f );
	m_camera.at  = float3( 0, 0, 0 );
	m_camera.up  = float3( 0, 1, 0 );

	m_camera.projectionType = Camera::PERSPECTIVE_FOV;
	m_camera.perspectiveFov.fovy = D3DXToRadian(45.f);
	m_camera.perspectiveFov.aspect = 1024.f/768.f;

	m_camera.zn = 1.0f;
	m_camera.zf = 100.0f;

	// initialize polygon
	m_box.push_back( float3( +0.1, -0.1, 0 ) );
	m_box.push_back( float3( +0.1, +0.1, 0 ) );
	m_box.push_back( float3( -0.1, +0.1, 0 ) );
	m_box.push_back( float3( -0.1, -0.1, 0 ) );

	// initialize first pos
	m_boxPos = zero3();

	// initialize polyline
	m_polyLine.push_back( float3( 0, 0, 0 ) );
	m_polyLine.push_back( float3( 1, 0, 0 ) );
	m_polyLine.push_back( float3( 1, 1, 0 ) );
	m_polyLine.push_back( float3( 2, 1, 0 ) );
}

Game::~Game()
{
	m_d3dDevice = 0;
}

void Game::onCreateGraphics( D3DDevice device )
{
	m_d3dDevice = device;
	m_boxView.initialize( m_d3dDevice );
	m_boxView.setup( m_box, float4( 1.0f, 1.0f, 1.0f, 1.0f ) );

	m_plView.initialize( m_d3dDevice );
	m_plView.setup( m_polyLine, float4( 1.0f, 0.2f, 0.6f, 0.6f ) );

	m_d3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CW );

	float44 world = identity44();
	float44 view = m_camera.view();
	float44 proj = m_camera.projection();

	m_d3dDevice->SetTransform( D3DTS_WORLD, &world );
	m_d3dDevice->SetTransform( D3DTS_VIEW, &view );
	m_d3dDevice->SetTransform( D3DTS_PROJECTION, &proj );
}

void Game::onResetGraphics( D3DDevice device )
{
	//TODO: Add code to handle lost device ( resizing issue )

	m_d3dDevice = device;

	m_d3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CW );

	float44 view = m_camera.view();
	float44 proj = m_camera.projection();

	m_d3dDevice->SetTransform( D3DTS_VIEW, &view );
	m_d3dDevice->SetTransform( D3DTS_PROJECTION, &proj );
}

void Game::onLostGraphics()
{
}

void Game::onFrameMove(float dt)
{
	IInput::MOUSESTATE mousestate;
	mousestate = m_input.mouseState();
	m_boxPos += float3( +mousestate.x / 50.f, -mousestate.y / 50.f, 0 );
}

void Game::onFrameRender(float dt)
{
	m_boxView.render( translation( m_boxPos ) );
	m_plView.render( identity44() );
	
	PolyLine::ClosestPointDesc closest = m_polyLine.closestPoint( m_boxPos );
	m_boxView.render( translation( closest.point ) );
}

void Game::onDestroyGraphics()
{
}
